package com.shenghua.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shenghua.dao.mapper.NoticeMapper;
import com.shenghua.dao.mapperX.NoticeMapperX;
import com.shenghua.dao.model.Notice;
import com.shenghua.dao.model.NoticeExample;
import com.shenghua.dao.page.Page;
import com.shenghua.service.NoticeService;
import com.shenghua.utils.PicUtil;
import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/1/31.
 */
@Service
public class NoticeServiceImpl implements NoticeService {
    Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private NoticeMapperX noticeMapperX;

    @Override
    public Dto<Notice> addNewNotice(Notice notice) {
        Dto<Notice> dto = new Dto<>();
        if(null == notice){
            logger.debug("[NoticeServiceImpl] addNewNotice 公告信息为空！");
            dto.ReturnFail(new Notice(), ErrorCode.NOTICE_IS_NULL);
            return dto;
        }
        NoticeExample noticeExample = new NoticeExample();
        NoticeExample.Criteria criteria = noticeExample.createCriteria();
        if(null != notice.getNoticeNo() && !"".equals(notice.getNoticeNo())) {
            criteria.andNoticeNoEqualTo(notice.getNoticeNo());
        }else {
            logger.debug("[NoticeServiceImpl] addNewNotice 公告编号不能为空！");
            dto.ReturnFail(new Notice(), ErrorCode.NOTICENO_IS_NULL);
            return dto;
        }
        List<Notice> noticeList = noticeMapper.selectByExample(noticeExample);
        if(noticeList.size()>0){
            logger.debug("[NoticeServiceImpl] addNewNotice 公告编号已经存在！");
            dto.ReturnFail(new Notice(), ErrorCode.NOTICENO_EXISTS);
            return dto;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
        notice.setEntryTime(new Date());

        int result = noticeMapper.insert(notice);
        if(result<=0){
            logger.debug("[NoticeServiceImpl] addNewNotice 模具信息添加失败！");
            dto.ReturnFail(new Notice(), ErrorCode.NOTICE_ADD_FAIL);
            return dto;
        }
        dto.ReturnSuccess(notice,ErrorCode.NOTICE_ADD_SUCCESS);
        logger.info("[NoticeServiceImpl] addNewNotice 公告信息添加成功！");
        logger.info("[NoticeServiceImpl] addNewNotice 准备添加的公告信息" + JSON.toJSONString(notice));
        return dto;
    }

    @Override
    public Dto<Map<String, Object>> queryNoticeByPage(Map<String, Object> params, Page page) {
        Dto<Map<String,Object>> dto = new Dto<>();
        if(null == params || params.size() == 0) {
            logger.debug("[NoticeServiceImpl] queryNoticeByPage 参数为空");
            dto.ReturnFail(null, ErrorCode.NOTICE_IS_NULL);
            return dto;
        }
        if(null == page){
            logger.debug("[NoticeServiceImpl] queryNoticeByPage 分页信息为空");
            dto.ReturnFail(null, ErrorCode.PAGE_IS_NULL);
            return dto;
        }
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 过滤查询条件
        Map<String,Object> map = new HashMap<>();
        if(null != params.get("noticeNo") && !"".equals(params.get("noticeNo"))){
            map.put("noticeNo",params.get("noticeNo"));
        }
        if(null != params.get("noticeTitle") && !"".equals(params.get("noticeTitle"))){
            map.put("noticeTitle",params.get("noticeTitle"));
        }
        if(null != params.get("remark") && !"".equals(params.get("remark"))){
            map.put("remark",params.get("remark"));
        }

        if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[NoticeServiceImpl] queryNoticeByPage 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        map.put("begin", page.getBegin());
        map.put("end", page.getLength());
        int total = 0;
        List<Notice> list = new ArrayList<>();
        List<Notice> list1 = null;
        list1 = noticeMapperX.selectNoticeListByMap(map);
        for(Notice item : list1) {
            item.setPicAddr(Constants.staticPrefix + item.getPicAddr());
            list.add(item);
        }
        total = noticeMapperX.countNoticeByMap(map);
        logger.info("***********************");
        logger.info("查询到的记录总数："+String.valueOf(total));
        logger.info("查询到的记录信息："+ JSON.toJSONString(list));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("total",total);
        paramMap.put("rows", list);
        dto.ReturnSuccess(paramMap,ErrorCode.NOTICE_QUERY_SUCCESS);
        return dto;
    }

    @Override
    public Dto<Notice> deleteNotice(Notice notice) {
        Dto<Notice> dto = new Dto<>();
        int id = notice.getId();
        int count = noticeMapper.deleteByPrimaryKey(id);
        if(count <= 0) {
            logger.debug("[NoticeServiceImpl] deleteNotice 公告删除失败！");
            dto.ReturnFail(notice,ErrorCode.NOTICE_DELETE_FAIL);
            return dto;
        }
        String picAddr = notice.getPicAddr();
        if(null != picAddr && !"".equals(picAddr)) {// 删除图片
            if(!new File(picAddr).exists()) {
                logger.debug("[NoticeServiceImpl] deleteNotice 公告图片不存在！");
                dto.ReturnSuccess(notice,ErrorCode.NOTICE_PIC_NOT_EXISTS);
                return dto;
            } else {
                boolean ret = PicUtil.DeleteImage(picAddr);
                if(!ret) {
                    logger.debug("[NoticeServiceImpl] deleteNotice 公告图片删除失败！");
                    dto.ReturnSuccess(notice,ErrorCode.NOTICE_DELETE_PIC_FAIL);
                    return dto;
                }
            }
        }
        logger.info("[NoticeServiceImpl] deleteNotice 公告删除成功！");
        dto.ReturnSuccess(notice,ErrorCode.NOTICE_DELETE_SUCCESS);
        return dto;
    }

    @Override
    public Notice selectNoticeById(int id) {
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        return notice;
    }

    @Override
    public Notice selectNoticeByNoticeNo(String noticeNo) {
        Notice notice = noticeMapperX.selectByNoticeNo(noticeNo);
        return notice;
    }

    @Override
    public Dto<Notice> editNotice(Notice notice) {
        return null;
    }

    @Override
    public Dto<Map<String, Object>> queryAllNotice(Map<String, Object> params) {
        Dto<Map<String,Object>> dto = new Dto<>();
        if(null == params || params.size() == 0) {
            logger.debug("[NoticeServiceImpl] queryAllNotice 参数为空");
            dto.ReturnFail(null, ErrorCode.NOTICE_IS_NULL);
            return dto;
        }
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 过滤查询条件
        Map<String,Object> map = new HashMap<>();
        if(null != params.get("noticeNo") && !"".equals(params.get("noticeNo"))){
            map.put("noticeNo",params.get("noticeNo"));
        }
        if(null != params.get("noticeTitle") && !"".equals(params.get("noticeTitle"))){
            map.put("noticeTitle",params.get("noticeTitle"));
        }
        if(null != params.get("remark") && !"".equals(params.get("remark"))){
            map.put("remark",params.get("remark"));
        }
        if(null != params.get("startTime") && !params.get("startTime").equals("") && null != params.get("endTime") && !params.get("endTime").equals("")){
            Date start = null;
            Date end = null;
            try {
                start = sif.parse(params.get("startTime").toString());
                end = sif.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                logger.info("[NoticeServiceImpl] queryNoticeByPage 时间解析异常！");
                e.printStackTrace();
            }
            map.put("startTime", start);
            map.put("endTime", end);
        }
        int total = 0;
        List<Notice> list = new ArrayList<>();
        List<Notice> list1 = null;
        list1 = noticeMapperX.selectNoticeListByMap(map);
        logger.info("[NoticeServiceImpl]QueryAllNotice {}", JSONObject.toJSON(list1));
        for(Notice item : list1) {
            item.setPicAddr(Constants.staticPrefix + item.getPicAddr());
            list.add(item);
        }
        total = noticeMapperX.countNoticeByMap(map);
        logger.info("***********************");
        logger.info("查询到的记录总数："+String.valueOf(total));
        logger.info("查询到的记录信息："+ JSON.toJSONString(list));
        logger.info("***********************");
        // 返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("total",total);
        paramMap.put("rows", list);
        dto.ReturnSuccess(paramMap,ErrorCode.NOTICE_QUERY_SUCCESS);
        return dto;
    }
}
